package neuralmusic.brain;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

import neuralmusic.brain.module.BasicDelayed;
import neuralmusic.brain.module.Scheduler;
import neuralmusic.brain.module.Neuron;


public class RTScheduler  extends Scheduler{

	TimeRef ref;
	
	DelayQueue<BasicDelayed> fireQueue=new DelayQueue<BasicDelayed>();
	
	
	public RTScheduler() {
		ref=new TimeRef();		
	}
	
	@Override
	public double getCurrentTimeInSecs() {		
		return ref.getCurrentTimeInSecs();
	}

	@Override
	public BasicDelayed take() throws InterruptedException {
		
		return fireQueue.take();
	}

	@Override
	public void add(BasicDelayed neuron) {
		fireQueue.add(neuron);
		
	}

	@Override
	public long getDelay(TimeUnit unit, double triggerInSecs) {
		long t = (long)((triggerInSecs - ref.getCurrentTimeInSecs())*1e6);		
		return unit.convert(t, TimeUnit.MICROSECONDS);	
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return 0;
	}

}


class TimeRef {
	 
	private long zero;
	
	public TimeRef() {
		zero =System.currentTimeMillis();
	}
	
	double getCurrentTimeInSecs() {
	        return  (double)(System.currentTimeMillis()-zero)/1000.0;
	}
	 
	long getStamp() {
	        return  System.currentTimeMillis()-zero;
   }

    final static TimeUnit timeUnit=TimeUnit.MILLISECONDS;

    double stampToSecs(long stamp){
    	return ((double)stamp)/1000.0;
    }
    
    static String unitname() {
        return "mS";
    }
 

	static long secToStamps(double delayInSecs) {
		
		return (long) (delayInSecs*1000);
	}


}
